import { getIndustryList } from '@/api/Plan';
import { Checkbox, Collapse, Spin } from 'antd';
import { memo, Ref, useEffect, useImperativeHandle, useMemo, useState } from 'react';
import OStyle from './index.less';
export type DicyType = {
  tradeDictName: string;
  tradeDictCode: string;
  isChecked?: boolean;
  tradeDictPosition?: [];
};
export type TradeType = {
  name: string;
  entTypeCode: string;
  /*
   *desc 是否选中
   */
  isChecked?: boolean;
  /*
   *desc 是否半选
   */
  indeterminate?: boolean;
  tradeDict: DicyType[];
};
function IndustrySel(props: {
  defaultValue: TradeType[];
  value?: any;
  initChange: any;
  onChange: any;
  innerRef: Ref<{ allSelect: (isChecked: any) => void } | undefined>;
}) {
  const [items, setItems] = useState<any[]>([]);
  const { defaultValue, innerRef, initChange, onChange } = props;
  // const [selectTrade, setSelectTrade] = useState<TradeType[]>();
  const [load, setLoad] = useState<boolean>(true);
  const [activeKey, setActiveKey] = useState<string[]>([]);
  useEffect(() => {
    setLoad(false);
    getIndustryList({}).then((value: any) => {
      initChange(value.length);
      console.log('有没有默认值', defaultValue);
      if (defaultValue.length) {
        //如果有默认值
        defaultValue.map((v) => {
          for (let i = 0; i < value.length; i++) {
            if (v.entTypeCode == value[i].entTypeCode) {
              value[i].tradeDict = value[i].tradeDict ? value[i].tradeDict : [];
              const defatultTradeCode = v.tradeDict.map((t: DicyType) => t.tradeDictCode);
              value[i].tradeDict.map((t: DicyType) => {
                if (defatultTradeCode.includes(t.tradeDictCode)) {
                  t.isChecked = true;
                }
              });
            }
          }
        });
        setItems(value);
      } else {
        setItems(value);
      }
      setLoad(true);
    });
  }, []);

  const { cItems, isAllSelect } = useMemo(() => {
    const _isAllSelect = false;
    const Keys: string[] = [];
    const _cItems = items.map((v: any) => {
      if (v.entTypeCode === 'consignor') {
        ////货主的行业分类不展示
        v.tradeDict = [];
      } else {
        v.tradeDict = v.tradeDict ? v.tradeDict : [];
      }

      const len = v.tradeDict.reduce((a: number, b: any) => {
        return a + (b.isChecked ? 1 : 0);
      }, 0);

      v.isChecked = v.tradeDict.length === len && len;
      v.indeterminate = len > 0 && !v.isChecked;
      Keys.push(v.guid);
      const result = {
        key: v.guid,
        label: (
          <Checkbox
            indeterminate={v.indeterminate}
            style={{ marginLeft: '16px' }}
            onChange={(e) => {
              v.tradeDict.forEach((val: any) => {
                val.isChecked = e.target.checked;
              });
              setItems((x) => {
                return x.slice();
              });
            }}
            checked={v.isChecked}
          >
            {v.name}({v.tradeDict.length})
          </Checkbox>
        ),
        children: v.tradeDict.map((val: any) => {
          return (
            <Checkbox
              key={val.tradeDictCode}
              checked={val.isChecked}
              style={{ lineHeight: '32px', margin: '0 8px' }}
              onChange={(e) => {
                val.isChecked = e.target.checked;
                setItems((x) => {
                  return x.slice();
                });
              }}
            >
              {val.tradeDictName}
            </Checkbox>
          );
        }),
      };
      return result;
    });
    if (Keys) {
      setActiveKey([...Keys]);
    }
    return {
      isAllSelect: _isAllSelect,
      cItems: _cItems.filter((v) => v.children.length),
    };
  }, [items]);

  const TradeParam = () => {
    const showTrade: TradeType[] = [];
    const codeList: string[] = [];
    const tradeNameList: string[] = [];
    let countTrade = 0;
    items.map((v: TradeType) => {
      if (v.tradeDict) {
        countTrade += v.tradeDict.length;
      }
      if (v.indeterminate || v.isChecked) {
        const tradeDictList: DicyType[] = [];
        v.tradeDict.map((t: DicyType) => {
          if (t.isChecked) {
            tradeDictList.push({
              tradeDictName: t.tradeDictName,
              tradeDictCode: t.tradeDictCode,
              tradeDictPosition: t.tradeDictPosition || [],
            });
            codeList.push(t.tradeDictCode);
            tradeNameList.push(t.tradeDictName);
          }
        });

        showTrade.push({
          name: v.name,
          entTypeCode: v.entTypeCode,
          tradeDict: tradeDictList,
        });
      }
    });

    onChange({
      showTrade: [...showTrade],
      code: codeList.join(','),
      tradeName: tradeNameList.join(','),
      isAllCheck: codeList.length == countTrade ? true : false,
    });
    // setSelectTrade([...showTrade]);
  };

  useEffect(() => {
    TradeParam();
  }, [items]);

  // useEffect(() => {
  //   onChange()
  // }, [load]);

  const allSelect = (isChecked: any) => {
    items.map((v: any) => {
      v.isChecked = isChecked;
      v.indeterminate = false;
      v.tradeDict.map((t: any) => {
        t.isChecked = isChecked;
      });
    });
    setItems([...items]);
  };

  //把事件给外面用
  useImperativeHandle(innerRef, () => ({
    allSelect,
  }));

  return (
    <>
      {load}
      {load ? (
        <Collapse
          className={OStyle.tradeGToupItemBox}
          style={{ border: 'none' }}
          items={cItems}
          defaultActiveKey={activeKey}
          expandIconPosition="end"
          collapsible="icon"
        />
      ) : (
        <div
          style={{
            display: 'flex',
            flexDirection: 'row',
            justifyContent: 'center',
            alignItems: 'center',
            height: '60px',
          }}
        >
          <Spin />
        </div>
      )}
    </>
  );
}
export default memo(IndustrySel);
